/**
 * WebsiteItem
 */

 import Validator from "../../../../../utils/validator/Validator";
 import tool from "../../../../../utils/tool";
 import React,{Component}from "react";

 class WebsiteItem extends Component{
    constructor(props) {
        super(props);
        this.state = {             
            url: ""
        };
    }
    componentWillMount(){
        const {data} = this.props;
        this.url = data.action.url || "";
        this.setState({
            url: this.url
        });
    }
    checkValidate(){
        let validator = Validator();

        validator.addRule($(this.refs.url), [{
            validator: "empty",
            error: $._('Link address can not empty')
        }, {
            validator: "url",
            error: $._("Link address error")
        }]);

        let errors = validator.execute();
        if (errors){
            alert(errors);
            return false;
        }
        return true;
    }
    handleOnChangeUrl(e){
        let element = $(e.target || e.srcElement);
        this.url = element.val();
        this.setState({
            url: this.url
        });
    }
    saveUrl(){
        if (this.checkValidate()){
            const {data: widget,updateWidget,setState} = this.props;
            this.url = tool.completionUrl(this.url);
            
            widget.action.url = this.url;
            this.setState({
                url: this.url
            });
            
            setState({selectedWidget: widget});
            updateWidget(widget);
        }
    }
    render(){
        const {data} = this.props;
        return (
            <input disabled={data.readOnly} ref="url" onBlur={() => this.saveUrl()} onChange={(e) => this.handleOnChangeUrl(e)} name="website" type="text" value={ this.state.url } />
        )
    }
 }

 module.exports = WebsiteItem;
